<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="btnCancal">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      label-width="120px"
      :model="formData"
      :rules="rules"
      ref="deptForm"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          style="width:80%"
          placeholder="1-50个字符"
          v-model="formData.name"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          style="width:80%"
          placeholder="1-50个字符"
          v-model="formData.code"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          style="width:80%"
          placeholder="请选择"
          v-model="formData.manager"
          @focus="getUserList"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          style="width:80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
          v-model="formData.introduce"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnClick"
          >确定</el-button
        >
        <el-button size="small" @click="btnCancal">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  getDepartment,
  addDepartment,
  getDepartDetail,
  updataDepartments
} from '@/api/department'
import { empList } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data () {
    // 现在定义一个函数 这个函数的目的是 去找 同级部门下 是否有重复的部门名称
    const checkNameRepeat = async (rule, value, callback) => {
      // 先要获取最新的组织架构数据
      const res = await getDepartment()
      let isRepeat = false
      if (this.formData.id) {
        // 有id 编辑规则
        isRepeat = res.data.depts
          .filter(
            item =>
              item.pid === this.treeNode.pid && item.id !== this.treeNode.id
          )
          .some(item => item.name === value)
      } else {
        isRepeat = res.data.depts
          .filter(item => item.pid === this.treeNode.id)
          .some(item => item.name === value)
      }
      // console.log(res)
      isRepeat
        ? callback(new Error(`同级部门下已经有${value}的部门了`))
        : callback()
    }

    const checkCodeREpeat = async (rule, value, callback) => {
      const res = await getDepartment()
      let isRepeat = false
      if (this.formData.id) {
        // 编辑
        isRepeat = res.data.depts
          .filter(item => item.id !== this.treeNode.id)
          .some(item => item.code === value && value)
      } else {
        isRepeat = res.data.depts.some(item => item.code === value && value)
      }

      isRepeat
        ? callback(new Error(`组织架构下已存在${value}编码了`))
        : callback()
    }
    return {
      // 定义表单数据
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { trigger: 'blur', validator: checkCodeREpeat }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      },
      // 员工列表
      userList: []
    }
  },
  methods: {
    async getUserList () {
      let res = await empList()
      console.log(res)
      this.userList = res.data
      // console.log(this.userList)
    },

    // 获取部门详情
    async getDepartDetail (id) {
      let res = await getDepartDetail(id)
      this.formData = res.data
      console.log(res)
    },

    // 新增部门
    btnClick () {
      this.$refs.deptForm.validate(async isOk => {
        if (isOk) {
          // 有id说明是编辑
          if (this.formData.id) {
            await updataDepartments(this.formData)
          } else {
            await addDepartment({
              ...this.formData,
              pid: this.treeNode.id
            })
          }

          // 告诉父组件
          this.$emit('addDepts')
          // 关闭模态框
          this.$emit('update:showDialog', false)
        }
      })
    },
    btnCancal () {
      // 重置数据 因为resetFields 只能重置表单中的数据
      this.formData = {}
      this.$refs.deptForm.resetFields()
      this.$emit('update:showDialog', false)
    }
  },
  computed: {
    showTitle () {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  }
}
</script>

<style></style>
